﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Ppt = Microsoft.Office.Interop.PowerPoint;
using Xl = Microsoft.Office.Interop.Excel;
using System.Runtime.InteropServices;

namespace ObjectModel.PowerPoint.RulesModel
{
    public static class ResolvableObjectExtensions
    {
        public static string SeriesToRangeAddress(this Ppt.Series series)
        {
            string[] args = series.Formula.Split(',');
            
            return args[2];
        }

        public static Xl.Range SeriesToRange(this ResolvableChartSeries series)
        {
            string address = SeriesToRangeAddress(series.Resolve() as Ppt.Series);
            
            // Replace with Regex
            string[] parts = address.Split('!');
            string sheetName = parts[0].Trim('\'');
            string localAddress = parts[1];

            Xl.Range range = null;

            try
            {
                Ppt.Shape sh = series.Shape.Resolve() as Ppt.Shape;
                Xl.Workbook wb = sh.Chart.ChartData.Workbook;
                Xl.Worksheet ws = wb.Worksheets[sheetName];
                range = ws.Range[localAddress];
            }
            catch (COMException) { throw; }

            return range;
        }

        public static Xl.Range PointToRange(this ResolvableChartPoint point)
        {
            Xl.Range seriesRange = SeriesToRange(point.Series);

            Xl.Range range = null;
            try { range = seriesRange.Item[point.PointIndex + 1]; }
            catch (COMException) { throw; }

            return range;
        }
    }
}
